package demo.android.com.mvpdemo.myRetrofit;

import java.io.IOException;

/**
 * Created by Vya on 2018/2/2 0002.
 */

public class OkHttpCall<T> implements Call<T> {
    final ServiceMethod serviceMethod;
    final Object[] args;
    public OkHttpCall(ServiceMethod serviceMethod, Object[] args) {
        this.serviceMethod = serviceMethod;
        this.args = args;
    }

    @Override
    public void enqueue(final Callback<T> callback) {
        //发起一个请求，然后给一个回调
         okhttp3.Call call = serviceMethod.createNewCall(args);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                if(callback != null){
                    callback.onFailure(OkHttpCall.this,e);
                }
            }

            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                //涉及解析，不能在这里写死，使用ConvertFactory
                Response rResponse = new Response();
                rResponse.body = serviceMethod.parseBody(response.body());

                if(callback != null){
                    callback.onResponse(OkHttpCall.this,rResponse);
                }

            }
        });
    }
}
